package com.ljx.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ljx.entity.TbSpecification;
import com.ljx.entity.TbSpecificationOption;
import com.ljx.entity.TbSpecificationOptionExample;
import com.ljx.mapper.TbSpecificationMapper;
import com.ljx.mapper.TbSpecificationOptionMapper;
import com.ljx.service.TbSpecificationOptionService;
import com.ljx.vo.TbSpecificationOptionVO;
import com.nanhang.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class TbSpecificationOptionServiceImpl implements TbSpecificationOptionService {
	@Autowired
	private TbSpecificationOptionMapper tbSpecificationOptionMapper;
	@Autowired
	private TbSpecificationMapper tbSpecificationMapper;

	@Override
	public List<TbSpecificationOption> findAll() {
		List<TbSpecificationOption> students = tbSpecificationOptionMapper.selectByExample(null);
		students.forEach(st -> {
			TbSpecification classes = tbSpecificationMapper.selectByPrimaryKey(st.getId());
			st.setSpecName(classes.getSpecName());
		});
		return students;
	}

	// 分页查询
	@Override
	public PageResult<TbSpecificationOption> findByPage(Integer page, Integer pageSize) {
		//1. 开始分页
		PageHelper.startPage(page,pageSize);
		// 2. 开始查询数据
		List<TbSpecificationOption> tbSpecificationOptions = this.findAll();
		// 3. 将查询得到的数据转换为Page<Student>对象
		PageInfo<TbSpecificationOption> tbSpecificationOptionPage = new PageInfo<>(tbSpecificationOptions);
		// 4. 转换为PageResult对象
		return new PageResult<>(tbSpecificationOptionPage.getList(), tbSpecificationOptionPage.getTotal());

	}

	// 条件查询带分页功能
	@Override
	public PageResult<TbSpecificationOption> search(Integer page, Integer pageSize, TbSpecificationOptionVO tbSpecificationOptionVO) {
		// 1. 开始分页
		PageHelper.startPage(page, pageSize);
		// 2. 查询数据
		// 2.1 定义一次查询的实例
		TbSpecificationOptionExample example = new TbSpecificationOptionExample();
		// 2.2 添加查询条件到查询实例中
		TbSpecificationOptionExample.Criteria criteria = example.createCriteria();
		if(tbSpecificationOptionVO.getSpecId() != null && tbSpecificationOptionVO.getSpecId() != 0){
			criteria.andSpecIdEqualTo(tbSpecificationOptionVO.getSpecId());
		}
		List<TbSpecificationOption> tbSpecificationOptions = tbSpecificationOptionMapper.selectByExample(example);
		tbSpecificationOptions.forEach(so -> {
			TbSpecification tbSpecification = tbSpecificationMapper.selectByPrimaryKey(so.getId());
			so.setSpecName(tbSpecification.getSpecName());
		});
		PageInfo<TbSpecificationOption> tbSpecificationOptionPage = new PageInfo<>(tbSpecificationOptions);
		return new PageResult<>(tbSpecificationOptionPage.getList(), tbSpecificationOptionPage.getTotal());

	}
	public boolean save(TbSpecificationOption tbSpecificationOption) {
		return tbSpecificationOptionMapper.insert(tbSpecificationOption) > 0;
	}
}